/*
Copyright (c) 2008  Franklin Schmidt <fschmidt@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package fschmidt.util.mail.javamail;

import java.util.NoSuchElementException;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.MessageRemovedException;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;

import fschmidt.util.mail.Mail;
import fschmidt.util.mail.MailException;
import fschmidt.util.mail.MailIterator;
import fschmidt.util.mail.Pop3Server;


final class Pop3ServerImpl implements Pop3Server {
	private final Properties props = new Properties();
	private Session session = null;
	private final String host;
	private final String username;
	private final String password;
	private boolean leaveOnServer = false;
	private int maxMailCount = Integer.MAX_VALUE;
	private Store store = null;

	Pop3ServerImpl(String machineName,String username,String password) {
		this.host = machineName;
		this.username = username;
		this.password = password;
	}

	public void setLeaveOnServer(boolean b) {
		this.leaveOnServer = b;
	}

	public void setMailLimit(int maxMailCount) {
		this.maxMailCount = maxMailCount;
	}

	public void useSsl() {
		props.setProperty( "mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.setProperty( "mail.pop3.port", "995");
		props.setProperty( "mail.pop3.socketFactory.port", "995");
	}

	public void setDebug(boolean b) {
		props.setProperty("mail.debug", Boolean.toString(b));
	}

	private synchronized Session getSession() {
		if( session==null ) {
			session = Session.getInstance(props);
		}
		return session;
	}

	public synchronized MailIterator getMail() throws MailException {
		if( store != null ) {
			store = null;
			throw new MailException("previous MailIterator not closed");
		}
		try {
			store = getSession().getStore("pop3");
			store.connect(host,username,password);
			final Folder folder = store.getFolder("INBOX");
			folder.open(Folder.READ_WRITE);
			final int nMsgs = Math.min(maxMailCount,folder.getMessageCount());
			return new MailIterator() {
				int i = 1;
				Mail nextMail = null;
				
				public boolean hasNext() throws MailException {
					//return i <= nMsgs;
					while (nextMail==null && i<=nMsgs) {
						try {
							MimeMessage msg = (MimeMessage)folder.getMessage(i++);
							if ( msg.isExpunged() || msg.isSet(Flags.Flag.DELETED) ) {
								continue;
							}
							if ( !leaveOnServer ) {
								msg.setFlag(Flags.Flag.DELETED,true);
							}
							nextMail = new MailImpl(msg);
						} catch (MessageRemovedException e) {
							// continue
						} catch (MessagingException e) {
							throw MailImpl.e(toString(),e);
						}
					}
					return nextMail!=null;
				}

				public Mail next() throws MailException, NoSuchElementException {
					try {
						if (nextMail==null && !hasNext())
							throw new NoSuchElementException();
						return nextMail;
					} finally {
						nextMail=null;
					}
				}

				public void close() throws MailException {
					try {
						if( folder.isOpen() )
							folder.close(true);
						store.close();
					} catch(MessagingException e) {
						throw MailImpl.e(toString(),e);
					} finally {
						store = null;
					}
				}
			};
		} catch(MessagingException e) {
			cleanup();
			throw MailImpl.e(toString(),e);
		}
	}

	private void cleanup() {
		if( store != null ) {
			try {
				store.close();
			} catch(MessagingException e2) {}
			store = null;
		}
	}

	public String getUsername() {
		return username;
	}

	public String toString() {
		return "Pop3ServerImpl("+host+","+username+","+password+")";
	}

}
